<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/5 0005
 * Time: 08:44
 */

namespace app\common\model;


use think\Exception;

class Staff extends BaseModel
{

    /**
     * 关联员工所在部门
     * @return \think\model\relation\BelongsTo
     */
    public function department() {
        return $this->belongsTo('Department');
    }

    /**
     * 获取员工列表
     * @param array $where
     * @param string $keyword
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($where = [], $keyword = '') {
        return self::with('department')->where($where)->where(function ($query) use ($keyword) {
            if ($keyword) {
                $query->where('name', '=', $keyword)->whereOr('job_number', '=', $keyword);
            }
        })->paginate(input('param.limit', 15), false, ['query' => input('param.')]);
    }

    /**
     * 创建或者编辑员工
     * @param $param
     * @param int $id
     * @return \think\response\Json
     */
    public static function createOrUpdateStaff($param, $id = 0) {
        try {
            if ($id > 0) {
                // 编辑
                $staff = self::get($id);
                if (!$staff) {
                    throw new Exception('员工不存在');
                }
                unset($param['job_number']);
                $staff->save($param);
            } else {
                $check_staff = self::where('job_number', '=', $param['job_number'])->find();
                if ($check_staff) {
                    throw new Exception('工号已存在');
                }
                // 添加
                self::create($param);
            }
            return return_data('success');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 获取作品参与者
     * @param $ids
     * @return string
     * @throws \think\exception\PDOException
     */
    public static function getParticipant($ids) {
        $data = self::where('id', 'in', $ids)->column('name');
        return implode(',', $data);
    }
}